package util;

import java.security.MessageDigest;

/**
 * HashUtil
 *
 * Helper for calculating hashes from byte[] and String. Will decode String's as
 * UTF-8. Uses a static salt for added security against rainbow tables.
 */
public class HashUtil {

    //TODO: Add user-specific salts.
    private static final String SALT = "i8&/Gf#rfs0?`<";

    public static String getSHA1(String source, boolean salt) {
        try {
            return getSHA1(source.getBytes("UTF-8"), salt);
        } catch (Exception e) {
            return getSHA1(source.getBytes(), salt);
        }
    }

    public static String getSHA1(byte[] source, boolean salt) {
        byte[] hash = null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            if (salt) {
                try {
                    md.update(SALT.getBytes("UTF-8"));
                } catch (Exception e) {
                    md.update(SALT.getBytes());
                }
            }
            hash = md.digest(source);

            StringBuilder sb = new StringBuilder(2 * hash.length);
            for (byte b : hash) {
                sb.append("0123456789ABCDEF".charAt((b & 0xF0) >> 4));
                sb.append("0123456789ABCDEF".charAt((b & 0x0F)));
            }
            return sb.toString();
        } catch (Exception e) {
        }
        return null;
    }
}
